package com.yzt.zhuju.widget.liveroom;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yzt.zhuju.R;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.SendGiftSuccessEvent;
import com.yzt.zhuju.event.main.UmoneyNotEnoughEvent;
import com.yzt.zhuju.gift.GiftBatterManager;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.gift.ChatRoomRewardData;
import com.yzt.zhuju.network.entity.gift.GiftBasisInfo;
import com.yzt.zhuju.network.entity.gift.GiftBatterInfo;
import com.yzt.zhuju.network.entity.gift.RewardData;
import com.yzt.zhuju.network.entity.gift.SelfSendGiftInfo;
import com.yzt.zhuju.network.entity.gift.SendChatRoomComboGiftResponse;
import com.yzt.zhuju.network.entity.gift.SendChatRoomGiftRequest;
import com.yzt.zhuju.network.entity.gift.SendGiftAnimViewInfo;
import com.yzt.zhuju.network.entity.gift.SendGiftRequest;
import com.yzt.zhuju.network.entity.gift.SendGiftResult;
import com.yzt.zhuju.utils.RechargeUtil;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.plugin_widget.RoundImageView;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * author : bob
 * date   : 2022/12/2
 * desc   :
 */
@SuppressLint("SetTextI18n")
public class SelfSendGiftAnimView extends FrameLayout {

    private final int[] itemBgs = {
            R.mipmap.item_gift_1,
            R.mipmap.item_gift_2,
            R.mipmap.item_gift_3,
            R.mipmap.item_gift_4,
    };

    private final Animation[] animations = new Animation[4];
    private final Animation[] animations200 = new Animation[4];
    private final Animation[] animations500 = new Animation[4];

    private int preItemBgIndex = 0;

    private final int middle = 200;
    private final int big = 500;

    private int getCurrentItemBgIndex() {
        int currentItemBgIndex = 0;
        if (preItemBgIndex == 0) {
            currentItemBgIndex = 1;
        }
        preItemBgIndex = currentItemBgIndex;
        return itemBgs[currentItemBgIndex];
    }

    private final List<GiftBasisInfo> giftBasisInfoList = new ArrayList<>();

    private Typeface mFont; //字体

    private RelativeLayout firstItem;
    private ImageView firstItemBg;
    private RoundImageView firstAvatar;
    private TextView firstName;
    private TextView firstInfo;
    private TextView tvFirstToName;
    private RoundImageView firstGiftView;
    private TextView firstGiftNum;

    private RelativeLayout secondItem;
    private ImageView secondItemBg;
    private RoundImageView secondAvatar;
    private TextView secondName;
    private TextView secondInfo;
    private TextView tvSecondToName;
    private RoundImageView secondGiftView;
    private TextView secondGiftNum;

    private RelativeLayout thirdItem;
    private ImageView thirdItemBg;
    private RoundImageView thirdAvatar;
    private TextView thirdName;
    private TextView thirdInfo;
    private TextView tvThirdToName;
    private RoundImageView thirdGiftView;
    private TextView thirdGiftNum;

    private RelativeLayout fourthItem;
    private ImageView fourthItemBg;
    private RoundImageView fourthAvatar;
    private TextView fourthName;
    private TextView fourthInfo;
    private TextView tvFourthToName;
    private RoundImageView fourthGiftView;
    private TextView fourthGiftNum;

    private boolean firstItemShowing = false;
    private boolean secondItemShowing = false;
    private long firstRemainingTime;
    private long secondRemainingTime;
    private long thirdRemainingTime;
    private long fourthRemainingTime;
    private TranslateAnimation horizontalTranslateAnim;
    private TranslateAnimation verticalTranslateAnim;

    private SendGiftAnimViewInfo firstGiftInfo;
    private SendGiftAnimViewInfo secondGiftInfo;
    private SendGiftAnimViewInfo thirdGiftInfo;
    private SelfSendGiftInfo fourthGiftInfo;
    private Animation receiveGiftAnim = null;

    private CountDownTimer firstCountDownTimer;
    private CountDownTimer secondCountDownTimer;
    private CountDownTimer thirdCountDownTimer;
    private CountDownTimer fourthCountDownTimer;
    private Timer sendGiftTimer;
    private MyTimeTask myTimeTask;
    private SelfSendGiftInfo lastSendGiftAnimViewInfo;

    private SVGAImageView treasure_chest;
    private SVGAParser treasure_chest_parser;
    private RelativeLayout rl_multiple;
    private TextView tv_multiple;

    private String roomId;
    private Activity activity;
    private boolean isNeedSend = true;
    private boolean isShowSend = false;

    private ObjectAnimator objectAnimatorX;

    public SelfSendGiftAnimView(Context context) {
        this(context, null);
    }

    public SelfSendGiftAnimView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SelfSendGiftAnimView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void initAnim(Context context, Animation[] animations, int id) {
        for (int i = 0; i < animations.length; i++) {
            animations[i] = AnimationUtils.loadAnimation(context, id);
        }
    }

    private void init(Context context) {
        receiveGiftAnim = AnimationUtils.loadAnimation(context, R.anim.anim_num_batter);
        initAnim(context, animations, R.anim.anim_num_batter);
        initAnim(context, animations200, R.anim.anim_num_batter200);
        initAnim(context, animations500, R.anim.anim_num_batter200);
        AssetManager mgr = context.getAssets();//得到AssetManager
        mFont = Typeface.createFromAsset(mgr, "fonts/num2.ttf");//根据路径得到Typeface
        View view = LayoutInflater.from(context).inflate(R.layout.item_send_gift_anim, null);
        addView(view);
        firstItem = view.findViewById(R.id.item_first);
        firstItemBg = view.findViewById(R.id.iv_first_item_bg);
        firstAvatar = view.findViewById(R.id.item_first_avatar);
        firstName = view.findViewById(R.id.tv_first_from_name);
        firstInfo = view.findViewById(R.id.tv_first_to_info);
        tvFirstToName = view.findViewById(R.id.tv_first_to_name);
        firstGiftView = view.findViewById(R.id.first_gift_view);
        firstGiftNum = view.findViewById(R.id.tv_first_gift_num);
        firstGiftNum.setTypeface(mFont);

        secondItem = view.findViewById(R.id.item_second);
        secondItemBg = view.findViewById(R.id.iv_second_item_bg);
        secondAvatar = view.findViewById(R.id.item_second_avatar);
        secondName = view.findViewById(R.id.tv_second_from_name);
        secondInfo = view.findViewById(R.id.tv_second_to_info);
        tvSecondToName = view.findViewById(R.id.tv_second_to_name);
        secondGiftView = view.findViewById(R.id.second_gift_view);
        secondGiftNum = view.findViewById(R.id.tv_second_gift_num);
        secondGiftNum.setTypeface(mFont);

        thirdItem = view.findViewById(R.id.item_third);
        thirdItemBg = view.findViewById(R.id.iv_third_item_bg);
        thirdAvatar = view.findViewById(R.id.item_third_avatar);
        thirdName = view.findViewById(R.id.tv_third_from_name);
        thirdInfo = view.findViewById(R.id.tv_third_to_info);
        tvThirdToName = view.findViewById(R.id.tv_third_to_name);
        thirdGiftView = view.findViewById(R.id.third_gift_view);
        thirdGiftNum = view.findViewById(R.id.tv_third_gift_num);
        thirdGiftNum.setTypeface(mFont);

        fourthItem = view.findViewById(R.id.item_fourth);
        fourthItemBg = view.findViewById(R.id.iv_fourth_item_bg);
        fourthAvatar = view.findViewById(R.id.item_fourth_avatar);
        fourthName = view.findViewById(R.id.tv_fourth_from_name);
        fourthInfo = view.findViewById(R.id.tv_fourth_to_info);
        tvFourthToName = view.findViewById(R.id.tv_fourth_to_name);
        fourthGiftView = view.findViewById(R.id.fourth_gift_view);
        fourthGiftNum = view.findViewById(R.id.tv_fourth_gift_num);
        fourthGiftNum.setTypeface(mFont);

        treasure_chest = view.findViewById(R.id.treasure_chest);
        rl_multiple = view.findViewById(R.id.rl_multiple);
        tv_multiple = view.findViewById(R.id.tv_multiple);
        treasure_chest.setClearsAfterStop(true);
        treasure_chest_parser = new SVGAParser(context);

        treasure_chest.setLoops(1);

        objectAnimatorX = ObjectAnimator.ofFloat(rl_multiple, "translationX", -getResources().getDimension(R.dimen.dp_150), getResources().getDimension(R.dimen.dp_25));
        objectAnimatorX.setDuration(500);
        receiveGiftAnim.setDuration(300);
        receiveGiftAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                rl_multiple.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        objectAnimatorX.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                rl_multiple.setVisibility(View.VISIBLE);
                super.onAnimationStart(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                rl_multiple.startAnimation(receiveGiftAnim);
            }
        });
    }

    public void setRoomId(String roomId) {
        this.roomId = roomId;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    /**
     * 显示收到礼物横幅
     */
    public void showReceiveGift(SendGiftAnimViewInfo giftInfo) {
        if (giftInfo == null) {
            return;
        }
        GiftBasisInfo basisInfo = new GiftBasisInfo(giftInfo);
        int index = giftBasisInfoList.indexOf(basisInfo);
        if (index > -1 && index < giftBasisInfoList.size()) {
            switch (giftBasisInfoList.get(index).getIndex()) {
                case 1:
                    updateFirstItemNum(giftInfo);
                    break;
                case 2:
                    updateSecondItemNum(giftInfo);
                    break;
                case 3:
                    updateThirdItemNum(giftInfo);
                    break;
            }
            return;
        }
        if (firstGiftInfo == null) {
            showFirstItem(giftInfo);
            return;
        }
        if (secondGiftInfo == null) {
            showSecondItem(giftInfo);
            return;
        }
        if (thirdGiftInfo == null) {
            showThirdItem(giftInfo);
            return;
        }
        showShortestTime(firstRemainingTime, secondRemainingTime, thirdRemainingTime, giftInfo);
    }

    public void showReceiveUbiGift(SendGiftAnimViewInfo giftInfo) {
        if (thirdGiftInfo != null && giftInfo.getGiftId() == thirdGiftInfo.getGiftId()) {
            updateThirdItemNum(giftInfo);
        } else {
            showThirdItem(giftInfo);
        }
    }

    /**
     * 替换剩余时间最短的横幅
     */
    private void showShortestTime(long time1, long time2, long time3, SendGiftAnimViewInfo giftInfo) {
        if (time1 < time2 && time1 < time3) {
            showFirstItem(giftInfo);
        } else if (time2 < time3) {
            showSecondItem(giftInfo);
        } else {
            showThirdItem(giftInfo);
        }
    }

    /**
     * 显示发送礼物横幅
     */
    public void showSendGift(SelfSendGiftInfo giftInfo, String roomId) {
        showSendGift(giftInfo, roomId, 2);
    }

    /**
     * 显示发送礼物横幅
     */
    public void showSendGift(SelfSendGiftInfo giftInfo, String roomId, int roomType) {
        if (giftInfo == null) {
            return;
        }
        if (!TextUtils.isEmpty(roomId)) {
            //更新钻石数量或者背包礼物
            if (giftInfo.getIsWareHouse() == 0) {
                double diamond = giftInfo.getWorth() * giftInfo.getGiftNum() * giftInfo.getList().size();
                double total = GiftBatterManager.getInstance().getDiamondNum();
                if (total < diamond) {
                    RxBus.getDefault().post(new UmoneyNotEnoughEvent(RechargeUtil.KEY_RECHARGE_DAMION));
                    return;
                }
                long t = (long) (total * 1000);
                long d = (long) (diamond * 1000);
                GiftBatterManager.getInstance().setDiamondNum(((double) (t - d)) / 1000);
            } else {
                GiftBatterManager.getInstance().updatePackGiftCountById(GiftBatterManager.getInstance().getPackGiftList(), giftInfo.getGiftId(), giftInfo.getGiftNum() * giftInfo.getList().size());
            }
        } else {
            if (giftInfo.getIsWareHouse() == 0) {
                double ubi = giftInfo.getWorth() * giftInfo.getGiftNum();
                double total = GiftBatterManager.getInstance().getUbiNUm();
                double activityUbiNum = GiftBatterManager.getInstance().getActivityUbiNum();
                if (giftInfo.getTypeId() == 1398) {
                    if (total - activityUbiNum < ubi) {
                        ToastUtil.showMessage("活动U币无法赠送幸运礼物");
                        RxBus.getDefault().post(new UmoneyNotEnoughEvent(RechargeUtil.KEY_RECHARGE_DAMION));
                        return;
                    }
                } else {
                    if (total < ubi) {
                        RxBus.getDefault().post(new UmoneyNotEnoughEvent(RechargeUtil.KEY_RECHARGE_DAMION));
                        return;
                    }
                }
                long t = (long) (total * 1000);
                long u = (long) (ubi * 1000);
                GiftBatterManager.getInstance().setUbiNUm(((double) (t - u)) / 1000);
            } else {
                GiftBatterManager.getInstance().updatePackGiftCountById(GiftBatterManager.getInstance().getUbiPackGiftList(), giftInfo.getGiftId(), giftInfo.getGiftNum());
            }
        }
        //礼物连击倒计时
        GiftBatterInfo giftBatter = GiftBatterManager.getInstance().getTimeByGiftId(giftInfo.getGiftId());
        boolean isCombo = false;
        if (giftBatter == null) {
            giftBatter = new GiftBatterInfo(giftInfo.getGiftId(), giftInfo.getGiftNum(), giftInfo.getComboTime() * 1000L, 0);
        } else {
            isCombo = true;
            giftBatter.setNumber(giftBatter.getNumber() + giftInfo.getGiftNum());
            giftBatter.setTime(giftInfo.getComboTime() * 1000L);
        }
        GiftBatterManager.getInstance().startCountdown(giftBatter, giftInfo, roomId);

        if (giftInfo.getTypeId() == 1397 || giftInfo.getTypeId() == 1398) {
            if (lastSendGiftAnimViewInfo != null && lastSendGiftAnimViewInfo.getGiftId() == giftInfo.getGiftId()) {
                lastSendGiftAnimViewInfo.setGiftNum(lastSendGiftAnimViewInfo.getGiftNum() + giftInfo.getGiftNum());
            } else {
                if (sendGiftTimer != null) {
                    sendGiftTimer.cancel();
                    sendGiftTimer = null;
                }
                if (myTimeTask != null) {
                    myTimeTask.cancel();
                    myTimeTask = null;
                }
                if (lastSendGiftAnimViewInfo != null) {
                    createSendGiftTimer(lastSendGiftAnimViewInfo.getTypeId());
                }
                lastSendGiftAnimViewInfo = new SelfSendGiftInfo();
                lastSendGiftAnimViewInfo.setGiftNum(giftInfo.getGiftNum());
                lastSendGiftAnimViewInfo.setUserName(giftInfo.getUserName());
                lastSendGiftAnimViewInfo.setGiftName(giftInfo.getGiftName());
                lastSendGiftAnimViewInfo.setGiftId(giftInfo.getGiftId());
                lastSendGiftAnimViewInfo.setGiftIcon(giftInfo.getGiftIcon());
                lastSendGiftAnimViewInfo.setUnit(giftInfo.getUnit());
                lastSendGiftAnimViewInfo.setExpired(giftInfo.getExpired());
                lastSendGiftAnimViewInfo.setKtId(giftInfo.getKtId());
                lastSendGiftAnimViewInfo.setList(giftInfo.getList());
                lastSendGiftAnimViewInfo.setTabId(giftInfo.getTabId());
                lastSendGiftAnimViewInfo.setType(giftInfo.getType());
                lastSendGiftAnimViewInfo.setTypeId(giftInfo.getTypeId());
                lastSendGiftAnimViewInfo.setWareHouseId(giftInfo.getWareHouseId());
            }
            createTimer();
        }

        if (isCombo && isShowSend && fourthGiftInfo != null && fourthGiftInfo.getUserName().equals(giftInfo.getUserName()) && fourthGiftInfo.getGiftId() == giftInfo.getGiftId()) {
            updateFourthItemNum(giftInfo);
        } else {
            showFourthItem(giftInfo, giftBatter.getNumber());
        }
    }

    private synchronized void createTimer() {
        if (sendGiftTimer == null) {
            sendGiftTimer = new Timer();
            myTimeTask = new MyTimeTask();
            sendGiftTimer.schedule(myTimeTask, 1000, 1000);
        }
    }

    private class MyTimeTask extends TimerTask {
        @Override
        public void run() {
            createSendGiftTimer(lastSendGiftAnimViewInfo.getTypeId());
        }
    }

    /**
     * 更新第一个礼物条目的数量
     */
    private void updateFirstItemNum(SendGiftAnimViewInfo giftInfo) {
        firstGiftInfo = giftInfo;
        createFirstCountDownTimer();
        firstGiftNum.setText("" + firstGiftInfo.getGiftNum());
        if (firstGiftInfo.getGiftNum() <= middle) {
            ((View) firstGiftNum.getParent()).startAnimation(animations[0]);
            firstItemBg.setImageResource(itemBgs[2]);
        } else if (firstGiftInfo.getGiftNum() <= big) {
            ((View) firstGiftNum.getParent()).startAnimation(animations200[0]);
            firstItemBg.setImageResource(itemBgs[1]);
        } else {
            ((View) firstGiftNum.getParent()).startAnimation(animations500[0]);
            firstItemBg.setImageResource(itemBgs[0]);
        }
    }

    /**
     * 更新第二个礼物条目的数量
     */
    private void updateSecondItemNum(SendGiftAnimViewInfo giftInfo) {
        secondGiftInfo = giftInfo;
        createSecondCountDownTimer();
        secondGiftNum.setText("" + secondGiftInfo.getGiftNum());
        if (secondGiftInfo.getGiftNum() <= middle) {
            ((View) secondGiftNum.getParent()).startAnimation(animations[1]);
            secondItemBg.setImageResource(itemBgs[2]);
        } else if (secondGiftInfo.getGiftNum() <= big) {
            ((View) secondGiftNum.getParent()).startAnimation(animations200[1]);
            secondItemBg.setImageResource(itemBgs[1]);
        } else {
            ((View) secondGiftNum.getParent()).startAnimation(animations500[1]);
            secondItemBg.setImageResource(itemBgs[0]);
        }
    }

    /**
     * 更新第三个礼物条目的数量
     */
    private void updateThirdItemNum(SendGiftAnimViewInfo giftInfo) {
        thirdGiftInfo = giftInfo;
        createThirdCountDownTimer();
        thirdGiftNum.setText("" + thirdGiftInfo.getGiftNum());
        if (thirdGiftInfo.getGiftNum() <= middle) {
            ((View) thirdGiftNum.getParent()).startAnimation(animations[2]);
            thirdItemBg.setImageResource(itemBgs[2]);
        } else if (thirdGiftInfo.getGiftNum() <= big) {
            ((View) thirdGiftNum.getParent()).startAnimation(animations200[2]);
            thirdItemBg.setImageResource(itemBgs[1]);
        } else {
            ((View) thirdGiftNum.getParent()).startAnimation(animations500[2]);
            thirdItemBg.setImageResource(itemBgs[0]);
        }
    }

    /**
     * 更新第四个礼物条目的数量
     */
    private void updateFourthItemNum(SelfSendGiftInfo giftInfo) {
        fourthGiftInfo.setGiftNum(fourthGiftInfo.getGiftNum() + giftInfo.getGiftNum());
        if (mSendGiftListener != null) {
            mSendGiftListener.sendComboGift(fourthGiftInfo);
        }
        createFourthCountDownTimer();
        fourthGiftNum.setText("" + fourthGiftInfo.getGiftNum());
        if (fourthGiftInfo.getGiftNum() <= middle) {
            ((View) fourthGiftNum.getParent()).startAnimation(animations[3]);
            fourthItemBg.setImageResource(itemBgs[3]);
        } else if (fourthGiftInfo.getGiftNum() <= big) {
            ((View) fourthGiftNum.getParent()).startAnimation(animations200[3]);
            fourthItemBg.setImageResource(itemBgs[1]);
        } else {
            ((View) fourthGiftNum.getParent()).startAnimation(animations500[3]);
            fourthItemBg.setImageResource(itemBgs[0]);
        }
    }

    /**
     * 展示第一个横幅
     */
    private void showFirstItem(SendGiftAnimViewInfo giftInfo) {
        if (activity.isDestroyed()) {
            return;
        }
        if (firstGiftInfo != null) {
            giftBasisInfoList.remove(new GiftBasisInfo(giftInfo));
        }
        giftBasisInfoList.add(new GiftBasisInfo(giftInfo, 1));
        firstGiftInfo = giftInfo;
        firstItemShowing = true;
        firstItem.setVisibility(VISIBLE);
        ImageLoadUtil.loadIv(firstAvatar.getContext(), firstGiftInfo.getFromAvatar(), firstAvatar);
        firstName.setText(firstGiftInfo.getFromNick());
        tvFirstToName.setText(getContext().getString(R.string.reward) + firstGiftInfo.getToNick());
        firstInfo.setText(firstGiftInfo.getGiftName());
        ImageLoadUtil.loadIv(firstGiftView.getContext(), firstGiftInfo.getGiftIcon(), firstGiftView);
        firstGiftNum.setText("" + firstGiftInfo.getGiftNum());
        if (firstGiftInfo.getGiftNum() <= middle) {
            firstItemBg.setImageResource(itemBgs[2]);
        } else if (firstGiftInfo.getGiftNum() <= big) {
            firstItemBg.setImageResource(itemBgs[1]);
        } else {
            firstItemBg.setImageResource(itemBgs[0]);
        }
        startHorizontalTranslateAnim(firstItem);
        createFirstCountDownTimer();
    }

    /**
     * 展示第二个横幅
     */
    private void showSecondItem(SendGiftAnimViewInfo giftInfo) {
        if (activity.isDestroyed()) {
            return;
        }
        if (secondGiftInfo != null) {
            giftBasisInfoList.remove(new GiftBasisInfo(giftInfo));
        }
        giftBasisInfoList.add(new GiftBasisInfo(giftInfo, 2));
        secondGiftInfo = giftInfo;
        secondRemainingTime = System.currentTimeMillis();
        secondItemShowing = true;
        secondItem.setVisibility(VISIBLE);
        ImageLoadUtil.loadIv(secondAvatar.getContext(), secondGiftInfo.getFromAvatar(), secondAvatar);
        secondName.setText(secondGiftInfo.getFromNick());
        tvSecondToName.setText(getContext().getString(R.string.reward) + secondGiftInfo.getToNick());
        secondInfo.setText(giftInfo.getGiftName());
        ImageLoadUtil.loadIv(secondGiftView.getContext(), giftInfo.getGiftIcon(), secondGiftView);
        secondGiftNum.setText("" + giftInfo.getGiftNum());
        if (secondGiftInfo.getGiftNum() <= middle) {
            secondItemBg.setImageResource(itemBgs[2]);
        } else if (secondGiftInfo.getGiftNum() <= big) {
            secondItemBg.setImageResource(itemBgs[1]);
        } else {
            secondItemBg.setImageResource(itemBgs[0]);
        }
        startHorizontalTranslateAnim(secondItem);
        createSecondCountDownTimer();
    }

    /**
     * 展示第三个横幅
     */
    private void showThirdItem(SendGiftAnimViewInfo giftInfo) {
        if (activity.isDestroyed()) {
            return;
        }
        if (thirdGiftInfo != null) {
            giftBasisInfoList.remove(new GiftBasisInfo(giftInfo));
        }
        giftBasisInfoList.add(new GiftBasisInfo(giftInfo, 3));
        thirdGiftInfo = giftInfo;
        thirdItem.setVisibility(VISIBLE);
        thirdItemBg.setImageResource(getCurrentItemBgIndex());
        ImageLoadUtil.loadIv(thirdAvatar.getContext(), thirdGiftInfo.getFromAvatar(), thirdAvatar);
        thirdName.setText(giftInfo.getFromNick());
        tvThirdToName.setText(getContext().getString(R.string.reward) + giftInfo.getToNick());
        thirdInfo.setText(giftInfo.getGiftName());
        ImageLoadUtil.loadIv(thirdGiftView.getContext(), giftInfo.getGiftIcon(), thirdGiftView);
        thirdGiftNum.setText("" + giftInfo.getGiftNum());
        if (thirdGiftInfo.getGiftNum() <= middle) {
            thirdItemBg.setImageResource(itemBgs[2]);
        } else if (thirdGiftInfo.getGiftNum() <= big) {
            thirdItemBg.setImageResource(itemBgs[1]);
        } else {
            thirdItemBg.setImageResource(itemBgs[0]);
        }
        startHorizontalTranslateAnim(thirdItem);
        createThirdCountDownTimer();
    }

    /**
     * 展示第四个横幅
     */
    private void showFourthItem(SelfSendGiftInfo giftInfo, int num) {
        if (activity.isDestroyed()) {
            return;
        }
        fourthGiftInfo = new SelfSendGiftInfo();
        fourthGiftInfo.setGiftNum(num);
        fourthGiftInfo.setUserName(giftInfo.getUserName());
        fourthGiftInfo.setGiftName(giftInfo.getGiftName());
        fourthGiftInfo.setGiftId(giftInfo.getGiftId());
        fourthGiftInfo.setGiftIcon(giftInfo.getGiftIcon());
        fourthGiftInfo.setUnit(giftInfo.getUnit());
        fourthGiftInfo.setExpired(giftInfo.getExpired());
        fourthGiftInfo.setKtId(giftInfo.getKtId());
        fourthGiftInfo.setList(giftInfo.getList());
        fourthGiftInfo.setTabId(giftInfo.getTabId());
        fourthGiftInfo.setType(giftInfo.getType());
        fourthGiftInfo.setTypeId(giftInfo.getTypeId());
        fourthGiftInfo.setWareHouseId(giftInfo.getWareHouseId());
        if (mSendGiftListener != null) {
            mSendGiftListener.sendComboGift(fourthGiftInfo);
        }
        fourthItem.setVisibility(VISIBLE);
        isShowSend = true;
        fourthItemBg.setImageResource(getCurrentItemBgIndex());
        ImageLoadUtil.loadIv(fourthAvatar.getContext(), RXingUtils.getLoginAccount().getUserInfo().getAvatar(), fourthAvatar);
        fourthName.setText(RXingUtils.getLoginAccount().getUserInfo().getUserName());
        if (fourthGiftInfo.getList() != null && fourthGiftInfo.getList().size() > 1) {
            tvFourthToName.setText(getContext().getString(R.string.reward) + fourthGiftInfo.getUserName() + "等" + fourthGiftInfo.getList().size() + "个人");
        } else {
            tvFourthToName.setText(getContext().getString(R.string.reward) + fourthGiftInfo.getUserName());
        }

        fourthInfo.setText(fourthGiftInfo.getGiftName());
        ImageLoadUtil.loadIv(fourthGiftView.getContext(), fourthGiftInfo.getGiftIcon(), fourthGiftView);
        fourthGiftNum.setText("" + fourthGiftInfo.getGiftNum());
        startHorizontalTranslateAnim(fourthItem);
        if (fourthGiftInfo.getGiftNum() <= middle) {
            fourthItemBg.setImageResource(itemBgs[3]);
        } else if (fourthGiftInfo.getGiftNum() <= big) {
            fourthItemBg.setImageResource(itemBgs[1]);
        } else {
            fourthItemBg.setImageResource(itemBgs[0]);
        }
        createFourthCountDownTimer();
    }

    /**
     * 两个Item是否同时在显示
     */
    public boolean isShowing() {
        return (firstItemShowing || firstItem.getVisibility() == VISIBLE)
                && (secondItemShowing || secondItem.getVisibility() == VISIBLE);
    }

    /**
     * 水平动画
     */
    private void startHorizontalTranslateAnim(View view) {
        horizontalTranslateAnim = new TranslateAnimation(DisplayUtils.getDisplayPxWidth(), 0, 0, 0);
        horizontalTranslateAnim.setDuration(500);
        horizontalTranslateAnim.setInterpolator(new DecelerateInterpolator());
        view.startAnimation(horizontalTranslateAnim);
    }

    /**
     * 垂直动画
     */
    private void startVerticalTranslateAnim(View view, int duration) {
        if (duration <= 0) {
            return;
        }
        verticalTranslateAnim = new TranslateAnimation(0, 0, 0, -DisplayUtils.dp2px(70));
        verticalTranslateAnim.setDuration(duration);
        verticalTranslateAnim.setInterpolator(new DecelerateInterpolator());
        verticalTranslateAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                setLayoutParam(view, false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(verticalTranslateAnim);
    }

    public void stopAnim() {
        if (horizontalTranslateAnim != null) {
            horizontalTranslateAnim.cancel();
        }
        if (verticalTranslateAnim != null) {
            verticalTranslateAnim.cancel();
        }
    }

    private void setLayoutParam(View view, boolean init) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
        if (init) {
            layoutParams.bottomMargin = DisplayUtils.dp2px(0);
        } else {
            layoutParams.bottomMargin = DisplayUtils.dp2px(10);
        }
        view.setLayoutParams(layoutParams);
    }

    private SendGiftListener mSendGiftListener;

    public void setSendGiftListener(SendGiftListener sendGiftListener) {
        this.mSendGiftListener = sendGiftListener;
    }

    public interface SendGiftListener {
        void sendGift(SelfSendGiftInfo info, boolean isNeedSend); //发送

        void sendComboGift(SelfSendGiftInfo info); //发送

        void sendUbiGift(SendGiftResult response, SelfSendGiftInfo giftInfo);
    }

    private void createFirstCountDownTimer() {
        if (firstCountDownTimer != null) {
            firstCountDownTimer.cancel();
            firstCountDownTimer = null;
        }
        firstCountDownTimer = new CountDownTimer(3000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                firstRemainingTime = millisUntilFinished;
            }

            @Override
            public void onFinish() {
                firstRemainingTime = 0;
                firstItem.setVisibility(INVISIBLE);
//				setLayoutParam(firstItem, true);
                firstItemShowing = false;
                isNeedSend = true;
                giftBasisInfoList.remove(new GiftBasisInfo(firstGiftInfo));
                firstGiftInfo = null;
            }
        };
        firstCountDownTimer.start();
    }

    private void createSecondCountDownTimer() {
        if (secondCountDownTimer != null) {
            secondCountDownTimer.cancel();
            secondCountDownTimer = null;
        }
        secondCountDownTimer = new CountDownTimer(3000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                secondRemainingTime = millisUntilFinished;
            }

            @Override
            public void onFinish() {
                secondRemainingTime = 0;
                secondItem.setVisibility(INVISIBLE);
//				setLayoutParam(secondItem, true);
                secondItemShowing = false;
                giftBasisInfoList.remove(new GiftBasisInfo(secondGiftInfo));
                secondGiftInfo = null;
            }
        };
        secondCountDownTimer.start();
    }

    private void createThirdCountDownTimer() {
        if (thirdCountDownTimer != null) {
            thirdCountDownTimer.cancel();
            thirdCountDownTimer = null;
        }
        thirdCountDownTimer = new CountDownTimer(3000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                thirdRemainingTime = millisUntilFinished;
            }

            @Override
            public void onFinish() {
                thirdRemainingTime = 0;
                thirdItem.setVisibility(INVISIBLE);
//				setLayoutParam(thirdItem, true);
                giftBasisInfoList.remove(new GiftBasisInfo(thirdGiftInfo));
                thirdGiftInfo = null;
            }
        };
        thirdCountDownTimer.start();
    }

    private void createFourthCountDownTimer() {
        if (fourthCountDownTimer != null) {
            fourthCountDownTimer.cancel();
            fourthCountDownTimer = null;
        }
        fourthCountDownTimer = new CountDownTimer(3000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                fourthRemainingTime = millisUntilFinished;
            }

            @Override
            public void onFinish() {
                fourthRemainingTime = 0;
                if (mSendGiftListener != null && fourthGiftInfo.getTypeId() != 1397 && fourthGiftInfo.getTypeId() != 1398) {
                    mSendGiftListener.sendGift(fourthGiftInfo, isNeedSend);
                }
                fourthItem.setVisibility(INVISIBLE);
                isShowSend = false;
                fourthGiftInfo = null;
                isNeedSend = true;
            }
        };
        fourthCountDownTimer.start();
    }

    private void createSendGiftTimer(int typeId) {
        if (lastSendGiftAnimViewInfo == null || lastSendGiftAnimViewInfo.getGiftNum() == 0) {
            if (sendGiftTimer != null) {
                sendGiftTimer.cancel();
                sendGiftTimer = null;
            }
            if (myTimeTask != null) {
                myTimeTask.cancel();
                myTimeTask = null;
            }
            return;
        }
        if (typeId == 1397) {
            sendComboGift(lastSendGiftAnimViewInfo, roomId);
        } else if (typeId == 1398) {
            sendComboUbiGift(lastSendGiftAnimViewInfo);
        }
        lastSendGiftAnimViewInfo.setGiftNum(0);
    }

    /**
     * 赠送U币连击礼物
     */
    public void sendComboUbiGift(SelfSendGiftInfo info) {
        if (info == null) {
            return;
        }
        SendGiftRequest mSendGiftRequest = new SendGiftRequest();
        mSendGiftRequest.setAmount(String.valueOf(info.getGiftId()));
        mSendGiftRequest.setIncomeUid(info.getList().get(0));
        mSendGiftRequest.setNum(info.getGiftNum());
        mSendGiftRequest.setIsWareHouse(info.getIsWareHouse());
        mSendGiftRequest.setTabId(info.getTabId());
//        BizLayer.getInstance().getGiftModule().postSendGiftToOther(mSendGiftRequest, new AresSubscriber<SendGiftResult>() {
//            @Override
//            protected void onSuccess(SendGiftResult response) {
//                if (mSendGiftListener != null) {
//                    mSendGiftListener.sendUbiGift(response, info);
//                }
//                RxBus.getDefault().post(new SendGiftSuccessEvent(info.getGiftId()));
//            }
//
//            @Override
//            protected void onError(int code, String i) {
//                super.onError(code, i);
//                if (code == 934) {
//                    RxBus.getDefault().post(new UmoneyNotEnoughEvent());
//                }
//            }
//        });
    }

    /**
     * 赠送连击礼物
     */
    public void sendComboGift(SelfSendGiftInfo info, String roomId) {
        if (info == null) {
            return;
        }
        StringBuilder userIds = new StringBuilder();
        for (int i = 0; i < info.getList().size(); i++) {
            if (i == 0) {
                userIds = new StringBuilder(info.getList().get(i));
            } else {
                userIds.append(",").append(info.getList().get(i));
            }
        }
        SendChatRoomGiftRequest mSendChatRoomGiftRequest = new SendChatRoomGiftRequest();
        mSendChatRoomGiftRequest.setGiftId(info.getGiftId());
        mSendChatRoomGiftRequest.setUidList(userIds.toString());
        mSendChatRoomGiftRequest.setGiftNum(info.getGiftNum());
        mSendChatRoomGiftRequest.setIsWareHouse(info.getIsWareHouse());
        mSendChatRoomGiftRequest.setRoomId(roomId);
        mSendChatRoomGiftRequest.setTabId(info.getTabId());
        mSendChatRoomGiftRequest.setWareHouseId(info.getWareHouseId());
        BizLayer.getInstance().getGiftModule().postSendMyChatRoomComboGift(mSendChatRoomGiftRequest, new AresSubscriber<SendChatRoomComboGiftResponse>() {
            @Override
            protected void onSuccess(SendChatRoomComboGiftResponse mSendChatRoomGiftResponse) {
                if (mSendChatRoomGiftResponse != null && mSendChatRoomGiftResponse.getRewardInfo() != null) {
                    double total = GiftBatterManager.getInstance().getDiamondNum();
                    GiftBatterManager.getInstance().setDiamondNum(total + mSendChatRoomGiftResponse.getRewardInfo().getRewardDiamondNum());
                }
            }
        });
    }

    public void stopRewardAnim() {
        treasure_chest.stopAnimation();
        treasure_chest.setVisibility(View.GONE);
        objectAnimatorX.end();
        rl_multiple.clearAnimation();
        rl_multiple.setVisibility(View.GONE);
    }

    public void startUbiRewardAnim(RewardData chatRoomRewardData) {
        stopRewardAnim();
        String rewardEffectUrl = chatRoomRewardData.getRewardEffectUrl();
        if (TextUtils.isEmpty(chatRoomRewardData.getRewardEffectUrl())) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rl_multiple.getLayoutParams();
            layoutParams.topMargin = (int) getResources().getDimension(R.dimen.dp_230);
            rl_multiple.setLayoutParams(layoutParams);
            rl_multiple.setVisibility(View.VISIBLE);
            tv_multiple.setText(chatRoomRewardData.getMultiple() + "倍");
            objectAnimatorX.start();
        } else {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) treasure_chest.getLayoutParams();
            layoutParams.topMargin = (int) getResources().getDimension(R.dimen.dp_150);
            treasure_chest.setLayoutParams(layoutParams);
            try {
                if (rewardEffectUrl.startsWith("http")) {
                    URL url = new URL(rewardEffectUrl);
                    treasure_chest_parser.parse(url, new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                            treasure_chest.setVisibility(VISIBLE);
                            SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
                            TextPaint textPaint = new TextPaint();
                            textPaint.setTypeface(mFont);
                            textPaint.setColor(Color.parseColor("#E61615"));
                            textPaint.setTextSize(getResources().getDimension(R.dimen.dp_10));
                            dynamicEntity.setDynamicText(chatRoomRewardData.getMultiple() + "倍", textPaint, "shuzi");
                            SVGADrawable drawable = new SVGADrawable(svgaVideoEntity, dynamicEntity);
                            treasure_chest.setImageDrawable(drawable);
                            treasure_chest.startAnimation();
                        }

                        @Override
                        public void onError() {

                        }
                    });
                } else {
                    treasure_chest_parser.parse(rewardEffectUrl, new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                            treasure_chest.setVideoItem(svgaVideoEntity);
                            treasure_chest.startAnimation();
                        }

                        @Override
                        public void onError() {

                        }
                    });
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }

    public void startUbiReceiveRewardAnim(ChatRoomRewardData chatRoomRewardData) {
        stopRewardAnim();
        String rewardEffectUrl = chatRoomRewardData.getRewardEffectUrl();
        if (TextUtils.isEmpty(chatRoomRewardData.getRewardEffectUrl())) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rl_multiple.getLayoutParams();
            layoutParams.topMargin = (int) getResources().getDimension(R.dimen.dp_170);
            rl_multiple.setLayoutParams(layoutParams);
            rl_multiple.setVisibility(View.VISIBLE);
            tv_multiple.setText(chatRoomRewardData.getRewardMultiple() + "倍");
            objectAnimatorX.start();
        } else {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) treasure_chest.getLayoutParams();
            layoutParams.topMargin = (int) getResources().getDimension(R.dimen.dp_90);
            treasure_chest.setLayoutParams(layoutParams);
            try {
                if (rewardEffectUrl.startsWith("http")) {
                    URL url = new URL(rewardEffectUrl);
                    treasure_chest_parser.parse(url, new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                            treasure_chest.setVisibility(VISIBLE);
                            SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
                            TextPaint textPaint = new TextPaint();
                            textPaint.setTypeface(mFont);
                            textPaint.setColor(Color.parseColor("#E61615"));
                            textPaint.setTextSize(getResources().getDimension(R.dimen.dp_10));
                            dynamicEntity.setDynamicText(chatRoomRewardData.getRewardMultiple() + "倍", textPaint, "shuzi");
                            SVGADrawable drawable = new SVGADrawable(svgaVideoEntity, dynamicEntity);
                            treasure_chest.setImageDrawable(drawable);
                            treasure_chest.startAnimation();
                        }

                        @Override
                        public void onError() {

                        }
                    });
                } else {
                    treasure_chest_parser.parse(rewardEffectUrl, new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                            treasure_chest.setVideoItem(svgaVideoEntity);
                            treasure_chest.startAnimation();
                        }

                        @Override
                        public void onError() {

                        }
                    });
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }

    public void startRewardAnim(ChatRoomRewardData chatRoomRewardData) {
        GiftBasisInfo basisInfo = new GiftBasisInfo();
        basisInfo.setFromName(chatRoomRewardData.getSendNickName());
        basisInfo.setToName(chatRoomRewardData.getReceiveName());
        basisInfo.setGiftId(chatRoomRewardData.getGiftId());
        int index = -1;
        if (chatRoomRewardData.getRewardUid().equals(RXingUtils.getUserId())) {
            index = 3;
        } else if (giftBasisInfoList.contains(basisInfo)) {
            index = giftBasisInfoList.indexOf(basisInfo);
        }
        if (index == -1) {
            return;
        }
        stopRewardAnim();
        String rewardEffectUrl = chatRoomRewardData.getRewardEffectUrl();
        if (TextUtils.isEmpty(chatRoomRewardData.getRewardEffectUrl())) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rl_multiple.getLayoutParams();
            layoutParams.topMargin = (int) (getResources().getDimension(R.dimen.dp_61) * (index + 1) - getResources().getDimension(R.dimen.dp_15));
            rl_multiple.setLayoutParams(layoutParams);
            tv_multiple.setText(chatRoomRewardData.getRewardMultiple() + "倍");
            objectAnimatorX.start();
        } else {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) treasure_chest.getLayoutParams();
            layoutParams.topMargin = (int) getResources().getDimension(R.dimen.dp_61) * index;
            treasure_chest.setLayoutParams(layoutParams);
            try {
                if (rewardEffectUrl.startsWith("http")) {
                    URL url = new URL(rewardEffectUrl);
                    treasure_chest_parser.parse(url, new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                            treasure_chest.setVisibility(VISIBLE);
                            SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
                            TextPaint textPaint = new TextPaint();
                            textPaint.setTypeface(mFont);
                            textPaint.setColor(Color.parseColor("#E61615"));
                            textPaint.setTextSize(getResources().getDimension(R.dimen.dp_10));
                            dynamicEntity.setDynamicText(chatRoomRewardData.getRewardMultiple() + "倍", textPaint, "shuzi");
                            SVGADrawable drawable = new SVGADrawable(svgaVideoEntity, dynamicEntity);
                            treasure_chest.setImageDrawable(drawable);
                            treasure_chest.startAnimation();
                        }

                        @Override
                        public void onError() {

                        }
                    });
                } else {
                    treasure_chest_parser.parse(rewardEffectUrl, new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                            treasure_chest.setVideoItem(svgaVideoEntity);
                            treasure_chest.startAnimation();
                        }

                        @Override
                        public void onError() {

                        }
                    });
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }
}
